package com.fundamental.server;

import sun.nio.ch.SelectionKeyImpl;
import sun.nio.ch.SelectorImpl;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;


public class NIOServer {


    private static NIOServer INSTANCE = new NIOServer();

    private ServerConfig config;

    private Selector selector;

    //服务器暂定为单线程
    private void start() throws IOException {
        try {
            ServerSocketChannel channel = ServerSocketChannel.open();
            ServerSocket serverSocket = channel.socket();
            channel.configureBlocking(false);
            serverSocket.bind(new InetSocketAddress(config.getAddress(), config.getPort()));
            channel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("服务器启动成功");
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
        //已经开始的服务器，不让他中断
        while (true) {
            try {
                selector.select();

                Set<SelectionKey> keySet = selector.selectedKeys();
                for(SelectionKey key : keySet){
                    try {
                        if (key.isAcceptable()) {

                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            SocketChannel channel = serverSocketChannel.accept();
                            channel.configureBlocking(false);
                            channel.register(selector, SelectionKey.OP_READ);
                            channel.register(selector,SelectionKey.OP_WRITE);
                            channel.write(ByteBuffer.wrap("连接成功".getBytes()));

                        } else if (key.isReadable()) {

                            SocketChannel channel = (SocketChannel) key.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            channel.read(buffer);
                            byte[] bytes = buffer.array();
                            String str = new String(bytes);
                            if (str.equals("time")) {
                                Date date = new Date();
                                System.out.println(date);
                                channel.write(ByteBuffer.wrap(SimpleDateFormat.getInstance().format(date).getBytes()));
                            } else {
                                System.out.println(str);
                                channel.write(ByteBuffer.wrap(bytes));
                            }

                        }else if(key.isWritable()){
                            key.channel();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        key.cancel();
                        key.channel().close();
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }


    public static void buildAndStart(ServerConfig serverConfig){

        try {
            INSTANCE.config = serverConfig;
            INSTANCE.selector = Selector.open();
            INSTANCE.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }







}
